package com.game.battle.common.math;

public class Segment2 {
	
	//Start point
	public Vector2 p0;
	// End point
	public Vector2 p1;

	public Vector2 center;

	public Vector2 direction;

	// Segment half-length
	public float extent;
	
	public Segment2(){
		
	}

	/// The constructor computes Center, Dircetion, and Extent from P0 and P1.
	/// <param name="p0">Segment start point</param>
	/// <param name="p1">Segment end point</param>
	public Segment2(Vector2 p0, Vector2 p1)
	{
		this.p0 = p0;
		this.p1 = p1;
		this.center = Vector2.zero;
		this.direction = Vector2.zero;
		this.extent = 0f;
		calcCenterDirectionExtent();
	}

	/// <summary>
	/// The constructor computes P0 and P1 from Center, Direction, and Extent.
	/// </summary>
	/// <param name="center">Center of the segment</param>
	/// <param name="direction">Direction of the segment. Must be unit length!</param>
	/// <param name="extent">Half-length of the segment</param>
	public Segment2(Vector2 center, Vector2 direction, float extent)
	{
		this.center = center;
		this.direction = direction;
		this.extent = extent;
		this.p0 = Vector2.zero;
		this.p1 = Vector2.zero;
		calcEndPoints();
	}			

	
	/// <summary>
	/// Initializes segments from endpoints.
	/// </summary>
	public void setEndpoints(Vector2 p0, Vector2 p1)
	{
		this.p0 = p0;
		this.p1 = p1;
		calcCenterDirectionExtent();
	}

	/// <summary>
	/// Initializes segment from center, direction and extent.
	/// </summary>
	public void setCenterDirectionExtent(Vector2 center, Vector2 direction, float extent)
	{
		this.center = center;
		this.direction = direction;
		this.extent = extent;
		calcEndPoints();
	}

	/// <summary>
	/// Call this function when you change P0 or P1.
	/// </summary>
	public void calcCenterDirectionExtent()
	{
		this.center =Vector2.multi(Vector2.add(p0, p1), 0.5f);
		this.direction = Vector2.sub(p1, p0);
		float directionLength = this.direction.getMagnitude();
		float invDirectionLength = 1f / directionLength;
		this.direction.multi(invDirectionLength);
		this.extent = 0.5f * directionLength;
	}

	/// <summary>
	/// Call this function when you change Center, Direction, or Extent.
	/// </summary>
	public void calcEndPoints()
	{
		p0 = Vector2.sub(this.center, Vector2.multi(this.direction, this.extent));
		p1 = Vector2.add(this.center, Vector2.multi(this.direction, this.extent));
	}

	/// <summary>
	/// Evaluates segment using (1-s)*P0+s*P1 formula, where P0 and P1
	/// are endpoints, s is parameter.
	/// </summary>
	/// <param name="s">Evaluation parameter</param>
	public Vector2 eval(float s)
	{
		return Vector2.add(Vector2.multi(p1, (1f - s)), Vector2.multi(p1,  s));
	}

	/// <summary>
	/// Returns distance to a point, distance is >= 0f.
	/// </summary>
	public float DistanceTo(Vector2 point)
	{
		return 0;
		//return Distance.Point2Segment2(ref point, ref this);
	}

}
